package com.jerry.Filter;

import com.alibaba.fastjson.JSON;
import com.jerry.response.CommonResponse;
import com.jerry.utils.BaseContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public final StringRedisTemplate redisTemplate;
    public final AntPathMatcher antPathMatcher;
    public LoginCheckFilter(StringRedisTemplate redisTemplate, AntPathMatcher antPathMatcher) {
        this.redisTemplate = redisTemplate;
        this.antPathMatcher = antPathMatcher;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String token = request.getHeader("Authorization");
        if (!token.isEmpty()){
            redisTemplate.expire(token,30, TimeUnit.MINUTES);
        }
        String uri = request.getRequestURI();
        String[] urls = new String[]{
                "user/**"
        };
        if (check(uri,urls)){
            filterChain.doFilter(request,response);
            return;
        }
        if (StringUtils.isNotEmpty(token)){
            BaseContext.setCurrentId(token);
            filterChain.doFilter(request,response);
            return;
        }
        response.getWriter().write(JSON.toJSONString(CommonResponse.error("NOTLOGIN")));
        return;
    }
    public Boolean check(String uri,String[] urls){
        for (String url : urls) {
            if(antPathMatcher.match(url,uri)){
                return true;
            }
        }
        return false;
    }
}
